package com.chenjl.transaction.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.chenjl.transaction.dao.TbRabbitmqSendLogMapper;
import com.chenjl.transaction.model.TbRabbitmqSendLog;

import lombok.extern.slf4j.Slf4j;
/**
 * 消息发送到交换器Exchange后触发回调
 * 2019-3-18 14:08:48
 * @author chenjinlong
 */
@Slf4j
@Service("rabbitMQConfirmCallback")
public class RabbitMQConfirmCallback implements ConfirmCallback {
	
	@Autowired
	private TbRabbitmqSendLogMapper tbRabbitmqSendLogMapper;
	
	
	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		log.info("ConfirmCallback...-->>--correlationData:{},boolean ack:{},cause:{}",JSONObject.toJSONString(correlationData),ack,cause);
		
		if(correlationData != null) {
			this.updateRabbitMqSendLog(correlationData,ack);
		}	
	}
	/**
	 * 更新exchange状态
	 * @param correlationData
	 * @param ack
	 */
	private void updateRabbitMqSendLog(CorrelationData correlationData,boolean ack) {		
		//从CorrelationData获取flowNo
		String flowNo = correlationData.getId();
		
		if(StringUtils.isNotBlank(flowNo)) {
			TbRabbitmqSendLog queryTbRabbitmqSendLog = new TbRabbitmqSendLog();
			queryTbRabbitmqSendLog.setFlowNo(flowNo);
			queryTbRabbitmqSendLog.setIsDeleted(false);
			List<TbRabbitmqSendLog> tbRabbitmqSendLogs = tbRabbitmqSendLogMapper.selectPageSelective(queryTbRabbitmqSendLog,new PageRequest(0,1));
			
			if(tbRabbitmqSendLogs.size() > 0) {
				TbRabbitmqSendLog tbRabbitmqSendLog = tbRabbitmqSendLogs.get(0);
			
				TbRabbitmqSendLog updateTbRabbitmqSendLog = new TbRabbitmqSendLog();
				updateTbRabbitmqSendLog.setId(tbRabbitmqSendLog.getId());
				updateTbRabbitmqSendLog.setExchangeStatus(ack);
				updateTbRabbitmqSendLog.setUpdateTime(new Date());
				tbRabbitmqSendLogMapper.updateByPrimaryKeySelective(updateTbRabbitmqSendLog);
			}
		}
	}
}